package haven.javafx.module.base;

import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

public abstract class BaseController extends Stage implements Initializable{
    public FXMLLoader loader=new FXMLLoader();
    public static Scene scene;
    Logger logger= LoggerFactory.getLogger(this.getClass());


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        init();
        bindEvent();
    }
    public abstract void init();
    public abstract void bindEvent();
    public void setScene(){
        loader.setLocation(this.getClass().getResource(getFXMLName()));
        try {
            scene=new Scene(loader.load());
            this.setScene(scene);
        } catch (IOException e) {
           logger.error(e.getMessage());
        }
    }
    final String getFXMLName(){
        String resourceAndLowerCase = getResourceAndLowerCase(".fxml");
        return resourceAndLowerCase;
    }
    String getResourceAndLowerCase(String ending){
        final String clazzWithending=this.getClass().getSimpleName();
        if(clazzWithending.endsWith("Controller")){
            int index = clazzWithending.lastIndexOf("Controller");
            String substring = clazzWithending.substring(0, index);
            return substring+ending;
        }else{
            logger.error("getResourceAndLowerCase error");
            return null;
        }
    }
}
